package com.yunhe.hibernate.test;

import com.yunhe.hibernate.entity.Clazz;
import com.yunhe.hibernate.entity.Specialty;
import com.yunhe.hibernate.entity.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
//        List<Student> list = session.createNativeQuery("select * from student").addEntity(Student.class).list();
        Query sss = session.getNamedQuery("sss");
        List list = sss.list();
        session.close();
    }



    public static void duixiang(SessionFactory sessionFactory){
        Session session = sessionFactory.openSession();
        List<Student> list = session.createQuery(" select new Student(s.name as name,s.height as height) from Student s ").list();
        session.close();
    }

    public static void list(SessionFactory sessionFactory){
        Session session = sessionFactory.openSession();
        List<List> list = session.createQuery(" select new list(s.name as name,s.height as height) from Student s ").list();
        session.close();
    }

    public static void map(SessionFactory sessionFactory){
        Session session = sessionFactory.openSession();
        List<Map> list = session.createQuery(" select new map(s.name as name,s.height as height) from Student s ").list();
        session.close();
    }

    public static void findOne(SessionFactory sessionFactory){
        Session session = sessionFactory.openSession();
        Student student = session.createQuery(" from Student ",Student.class).uniqueResult();
        session.close();
    }

    public static void findList(SessionFactory sessionFactory){
        Session session = sessionFactory.openSession();
        Query query = session.createQuery(" from Student");
        List<Student> list = query.list();
        session.close();
    }

    public static void save(SessionFactory sessionFactory){
        Student student = new Student();
        student.setName("ee");
        student.setBirthday(new Date());


        Clazz clazz = new Clazz();
        clazz.setName("2班");

        Specialty specialty = new Specialty();
        specialty.setName("UI");
        Session session = sessionFactory.openSession();

//        Clazz clazz = session.find(Clazz.class, 2);

        student.setClazz(clazz);
        clazz.setSpecialty(specialty);

        Transaction transaction = session.beginTransaction();
        session.persist(student);
        transaction.commit();
        session.close();
    }
}
